import os
import yaml
import logging.config
import atexit
import fcntl

from flask import Flask
from flask_cors import CORS
from flask_apscheduler import APScheduler

from .web import manage as manage_blueprint
from app.common.redis import redis_cli
from app.common.logging import MidnightRotatingFileHandler


def get_basedir():
    """
    获取应用的根目录
    :return:
    """
    return os.path.abspath(os.path.dirname(__file__))


def create_app():
    """
    创建应用
    :return:
    """

    manage_app = Flask(__name__)
    # 字符串支持中文显示
    manage_app.config['JSON_AS_ASCII'] = False
    manage_app.config["SECRET_KEY"] = 'af2fad8cfe1f4c5fac4aa5edf6fcc8f3'
    manage_app.register_blueprint(manage_blueprint)

    # 支持跨域
    CORS(manage_app, supports_credentials=True)

    return manage_app


def init_scheduler_app(app):
    f = open("scheduler.lock", "wb")
    try:
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        scheduler = APScheduler()
        scheduler.init_app(app)
        scheduler.start()
    except:
        pass

    def unlock():
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()

    atexit.register(unlock)


def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):
    path = get_basedir() + "/" + default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = yaml.load(f.read())
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)
